﻿/*******************************************************************************
 * Copyright @ 2017 YunSpace.Framework 版权所有
 * Author: GaoTang
 * Description: YunSpace 快速开发平台
 * Website：http://www.yunspace.com.cn
*********************************************************************************/
#region USING SYSTEM
using YunSpace.Core;
using YunSpace.Domain.Entity.SiteLibraryManage;
using YunSpace.Domain.IRepository.SiteLibraryManage;
using YunSpace.Repository.SiteLibraryManage;
using System.Collections.Generic;
using System.Linq;
using YunSpace.Application.SystemManage;
using YunSpace.Domain.Entity.SystemManage;
using YunSpace.Repository.MiniSite;
using YunSpace.Domain.IRepository.MiniSite;
using YunSpace.Domain.ViewModel.MiniSite;
using YunSpace.Domain.ViewModel.SiteLibraryManage;
using YunSpace.Data;
using System.Data.Common;
using MySql.Data.MySqlClient;
using YunSpace.Domain.ViewModel;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Domain.ViewModel.MiniSite;
using System;
using YunSpace.Domain.Entity.SiteMgr;
using YunSpace.Domain.IRepository.SiteMgr;
using YunSpace.Repository.SiteMgr;
using YunSpace.Domain.ViewModel.SiteMgr;
using YunSpace.Domain.Entity.OrderFlowManage;
using YunSpace.Domain.IRepository.OrderFlowManage;
using YunSpace.Repository.OrderFlowManage;
using YunSpace.Domain.Entity;
using YunSpace.Domain.ViewModel.StatisticalForm;
using YunSpace.Domain.ViewModel.ClientManager;
using YunSpace.Domain.ViewModel.WeChat;

#endregion

namespace YunSpace.Application.SiteLibraryManage
{
    public class SiteApp
    {
        private ISiteRepository service = new SiteRepository();
        private ICheckRecordRepository checkService = new CheckRecordRepository();
        private IMessageNoticeRepository messageService = new MessageNoticeRepository(); 
        private ISiteOrderRepository orderService = new SiteOrderRepository();
        private ICommentRepository commentService = new CommentRepository();
        private ISiteActivityRepository activityService = new SiteActivityRepository();
        private ISiteVistorRecordRepository siteVistor = new SiteVistorRecordRepository();
        private PhotosApp photosApp = new PhotosApp();


        private ItemsDetailApp itemsDetailApp = new ItemsDetailApp();

        public List<SiteEntity> GetList(string keyword = "")
        {
            var expression = ExtLinq.True<SiteEntity>();
            expression.And(t => t.state >= 0);
            return service.IQueryable(expression).OrderBy(t => t.F_Id).ToList();
        }


        public List<SiteEntity> GetList(Pagination pagination, string queryJson,string uid)
        {
            var result = new List<SiteEntity>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select distinct si.* from SL_Site si left join SL_Space sp 
                             on (si.F_Id = sp.F_SiteId) 
                             where 1=1 and F_SupplierId=@uid {0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11} ";
                var countSql = @"select Count(1) from (select distinct si.F_Id from SL_Site si left join SL_Space sp 
                             on (si.F_Id = sp.F_SiteId) where 1=1 and F_SupplierId=@uid {0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}) as t";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@uid",uid),
                    new MySqlParameter("@state", queryParam["state"]),
                    new MySqlParameter("@through_three_areas",queryParam["through_three_areas"]),
                    new MySqlParameter("@site_type", queryParam["site_type"]),
                    new MySqlParameter("@provinces_id", queryParam["provinces_id"]),
                    new MySqlParameter("@city", queryParam["city"]),
                    new MySqlParameter("@district", queryParam["district"]),
                    new MySqlParameter("@business_area", queryParam["business_area"]),
                    new MySqlParameter("@min_area", queryParam["min_area"]),
                    new MySqlParameter("@max_area", queryParam["max_area"]),
                    new MySqlParameter("@height", queryParam["height"]),
                    new MySqlParameter("@max_seating_capacity", queryParam["max_seating_capacity"]),
                    new MySqlParameter("@min_inner_price", queryParam["min_inner_price"]),
                    new MySqlParameter("@max_inner_price", queryParam["max_inner_price"]),
                };

                if (!queryParam.IsEmpty())
                {
                    //最大最小面积
                    var areasql = "";
                     if (!queryParam["min_area"].IsEmpty() && !queryParam["max_area"].IsEmpty())
                    {
                        areasql = " and sp.area between @min_area and @max_area ";
                    }
                    else if (!queryParam["min_area"].IsEmpty())
                    {
                        areasql = " and sp.area > @min_area";
                    }
                    else if (!queryParam["max_area"].IsEmpty())
                    {
                        areasql = " and sp.area < @max_area";
                    }
                    //最大最小单价
                    var inner_price = "";
                    if (!queryParam["min_inner_price"].IsEmpty() && !queryParam["max_inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice between @min_inner_price and @max_inner_price ";
                    }
                    else if (!queryParam["inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice > @min_inner_price";
                    }
                    else if (!queryParam["max_inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice < @max_inner_price";
                    }
                    strSql = string.Format(strSql, queryParam["keyword"].IsEmpty() ? "" : " AND (si.title LIKE'%" + 
                        queryParam["keyword"] + "%' or si.nickname  LIKE'%" + queryParam["keyword"] + "%')",
                        queryParam["state"].IsEmpty() ? " and (si.state=1 or si.state=3 or si.state=5)" : " and si.state =@state ",
                        queryParam["site_type"].IsEmpty() ? "" : " and si.site_type=@site_type ",
                        queryParam["provinces_id"].IsEmpty() ? "" : " and si.provinces_id=@provinces_id ",
                        queryParam["city"].IsEmpty() ? "" : " and si.city_id=@city ",
                        queryParam["district"].IsEmpty() ? "" : " and si.district_id=@district ",
                        queryParam["business_area"].IsEmpty() ? "" : " and si.business_area = @business_area",
                        areasql,
                        queryParam["height"].IsEmpty() ? "" : " and sp.height=@height ",
                        queryParam["max_seating_capacity"].IsEmpty() ? "" : " and sp.max_seating_capacity=@max_seating_capacity ",
                        queryParam["through_three_areas"].IsEmpty() ? "" : " and sp.through_three_areas LIKE'%" + queryParam["through_three_areas"] + "%'",
                        inner_price);

                    countSql = string.Format(countSql, queryParam["keyword"].IsEmpty() ? "" : " AND (si.title LIKE'%" + 
                        queryParam["keyword"] + "%' or si.nickname  LIKE'%" + queryParam["keyword"] + "%')",
                        queryParam["state"].IsEmpty() ? "" : " and si.state =@state ",
                        queryParam["site_type"].IsEmpty() ? "" : " and si.site_type=@site_type ",
                        queryParam["provinces_id"].IsEmpty() ? "" : " and si.provinces_id=@provinces_id ",
                        queryParam["city"].IsEmpty() ? "" : " and si.city_id=@city ",
                        queryParam["district"].IsEmpty() ? "" : " and si.district_id=@district ",
                        queryParam["business_area"].IsEmpty() ? "" : " and si.business_area = @business_area",
                        areasql,
                        queryParam["height"].IsEmpty() ? "" : " and sp.height=@height ",
                        queryParam["max_seating_capacity"].IsEmpty() ? "" : " and sp.max_seating_capacity=@max_seating_capacity ",
                        queryParam["through_three_areas"].IsEmpty() ? "" : " and sp.through_three_areas LIKE'%" + queryParam["through_three_areas"] + "%'",
                        inner_price);
                }

               
                int startNo = pagination.rows * (pagination.page - 1);
                int endNo = startNo + pagination.rows;

                //strSql = string.Format("{0} ORDER BY si.{1}", strSql, pagination.sidx);

                strSql = string.Format("{0} order by si.F_LastModifyTime desc LIMIT {1},{2};", strSql, startNo, endNo);
                
                int count = service.Count(countSql, parameter);
                pagination.records = count;
                result = db.FindList<SiteEntity>(strSql,parameter);
            }
            return result;
        }

        public List<SiteSpaceEntity> GetsSpaceList(string queryJson)
        {
            var result = new List<SiteSpaceEntity>();
            using (var db = new RepositoryBase())
            {
                var strSql = @"select si.city_id, si.title,si.district_id,si.address, si.recommend_reason,si.business_area,
                             sma.sign_brand,
							(select sid.F_ItemName from Sys_ItemsDetail sid,Sys_Items si where si.F_Id=sid.F_ItemId and si.F_EnCode='StoreType' and sid.F_ItemCode=sma.F_StoreType)F_StoreType,
							(select sid.F_ItemName from Sys_ItemsDetail sid,Sys_Items si where si.F_Id=sid.F_ItemId and si.F_EnCode='AverageConsumer' and sid.F_ItemCode=sma.F_Average_Consumer)F_Average_Consumer,
							(select sid.F_ItemName from Sys_ItemsDetail sid,Sys_Items si where si.F_Id=sid.F_ItemId and si.F_EnCode='GuestType' and sid.F_ItemCode=sma.F_GuestType)F_GuestType
                            ,sp.visitors,sp.weekend_flow,sp.title as spacetitle,sp.through_three_areas,sp.area,sp.current_floor, 
                            sp.height,sp.F_ordinary_MarketPrice,sp.F_MarketPrice,
   						    (select sid.F_ItemName from Sys_ItemsDetail sid,Sys_Items si where si.F_Id=sid.F_ItemId and si.F_EnCode='units' and sid.F_ItemCode=sp.F_Units)F_Units,
							case 
    							when sp.quote_explain = 0 then '不含税'
									when sp.quote_explain = 1 then '含税'
									end quote_explain,
                            (SELECT GROUP_CONCAT(F_ActivitiesTitle)F_ActivitiesTitle  
									 FROM Site_ActivitiesCase sac 
									 WHERE sac.F_SiteId = si.F_Id )Activities,
                            sp.F_PriceDes 
                            from  SL_Space sp
                            left join Space_Market_Attrs sma on (sma.F_SpaceId=sp.F_Id) 
                            inner join SL_Site si on (si.F_Id = sp.F_SiteId)  
                            where sp.state=1 and si.state=1 {0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}  
                            order by si.F_CreatorTime desc";
                var queryParam = queryJson.ToJObject();
                DbParameter[] parameter =
                {
                    new MySqlParameter("@state", queryParam["state"]),
                    new MySqlParameter("@through_three_areas",queryParam["through_three_areas"]),
                    new MySqlParameter("@site_type", queryParam["site_type"]),
                    new MySqlParameter("@city", queryParam["city"]),
                    new MySqlParameter("@district", queryParam["district"]),
                    new MySqlParameter("@business_area", queryParam["business_area"]),
                    new MySqlParameter("@min_area", queryParam["min_area"]),
                    new MySqlParameter("@max_area", queryParam["max_area"]),
                    new MySqlParameter("@height", queryParam["height"]),
                    new MySqlParameter("@max_seating_capacity", queryParam["max_seating_capacity"]),
                    new MySqlParameter("@min_inner_price", queryParam["min_inner_price"]),
                    new MySqlParameter("@max_inner_price", queryParam["max_inner_price"]),
                };

                if (!queryParam.IsEmpty())
                {
                    //最大最小面积
                    var areasql = "";
                    if (!queryParam["min_area"].IsEmpty() && !queryParam["max_area"].IsEmpty())
                    {
                        areasql = " and sp.area between @min_area and @max_area ";
                    }
                    else if (!queryParam["min_area"].IsEmpty())
                    {
                        areasql = " and sp.area > @min_area";
                    }
                    else if (!queryParam["max_area"].IsEmpty())
                    {
                        areasql = " and sp.area < @max_area";
                    }
                    //最大最小单价
                    var inner_price = "";
                    if (!queryParam["min_inner_price"].IsEmpty() && !queryParam["max_inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice between @min_inner_price and @max_inner_price ";
                    }
                    else if (!queryParam["inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice > @min_inner_price";
                    }
                    else if (!queryParam["max_inner_price"].IsEmpty())
                    {
                        inner_price = " and sp.F_MarketPrice < @max_inner_price";
                    }
                    string keyvalues = "";
                    if (!queryParam["keyvalues"].IsEmpty()) {
                        keyvalues = " and si.F_Id in('"+queryParam["keyvalues"] +"')";
                    }
                    strSql = string.Format(strSql, queryParam["keyword"].IsEmpty() ? "" : " AND (si.title LIKE'%" + queryParam["keyword"] + "%' or si.nickname  LIKE'%" + queryParam["keyword"] + "%')",
                        queryParam["state"].IsEmpty() ? "" : " and si.state =@state ",
                        queryParam["site_type"].IsEmpty() ? "" : " and si.site_type=@site_type ",
                        queryParam["city"].IsEmpty() ? "" : " and si.city_id=@city ",
                        queryParam["district"].IsEmpty() ? "" : " and si.district_id=@district ",
                        queryParam["business_area"].IsEmpty() ? "" : " and si.business_area = @business_area",
                        areasql,
                        queryParam["height"].IsEmpty() ? "" : " and sp.height`=@height ",
                        queryParam["max_seating_capacity"].IsEmpty() ? "" : " and sp.max_seating_capacity=@max_seating_capacity ",
                        queryParam["through_three_areas"].IsEmpty() ? "" : " and sp.through_three_areas LIKE'%" + queryParam["through_three_areas"] + "%'",
                        inner_price,
                        queryParam["keyvalues"].IsEmpty() ? "" : keyvalues);
                }
                result = db.FindList<SiteSpaceEntity>(strSql, parameter);
                queryParam = queryJson.ToJObject();
            }
            return result;
        }

        public SiteEntity GetSite(string keyValue)
        {
            return service.FindEntity(keyValue);
        }

        public List<PhotosEntity> GetPhoto(string keyValue)
        {
            using(var db=new RepositoryBase())
            {
                string strSql = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='Site' and F_DeleteMark=0;";
                var data = db.FindList<PhotosEntity>(strSql);
                return data;
            }
        }

        public SiteInfoOutput GetForm(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                SiteInfoOutput data = new SiteInfoOutput();
                string strSql1 = @"select * from SL_Site where F_Id='" + keyValue + "';";
                string strSql2 = @"select * from Site_Financial where f_SiteId='" + keyValue + "';";
                string strSql3 = @"select * from Site_TheContract where f_SiteId='" + keyValue + "';";
                string strSql4 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='SiteFiles' and F_DeleteMark=0;";
                string strSql5 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='Site' and F_DeleteMark=0;";
                string strSql6 = @"select * from SL_Photos where photoable_id='" + keyValue + "' and photoable_type='SiteVideo' and F_DeleteMark=0;";

                var data1 = db.FindList<SiteEntity>(strSql1);
                var data2 = db.FindList<FinancialEntity>(strSql2);
                var data3 = db.FindList<TheContractEntity>(strSql3);
                var data4 = db.FindList<PhotosEntity>(strSql4);
                var data5 = db.FindList<PhotosEntity>(strSql5);
                var data6 = db.FindList<PhotosEntity>(strSql6);
                data.siteEntity = data1.FirstOrDefault();
                data.financialEntity = data2.FirstOrDefault();
                data.theContractEntity = data3.FirstOrDefault();
                data.FilesList = data4;
                data.PhotosList = data5;
                data.VideoList = data6;

                return data;

            }

            //return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(SiteEntity siteEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                siteEntity.Modify(keyValue);
                service.Update(siteEntity);
                //SubmitMessager(siteEntity, "update");
            }
            else
            {
                siteEntity.Create();
                siteEntity.F_LastModifyTime = siteEntity.F_CreatorTime;
                siteEntity.F_LastModifyUserId = siteEntity.F_CreatorUserId;
                // siteEntity.F_Category = 2;
                service.Insert(siteEntity);
                //SubmitMessager(siteEntity, "add");
            }
        }


        /// <summary>
        /// 新增、修改场地空间数据提交审核申请及消息推送
        /// </summary>
        /// <param name="siteEntity"></param>
        /// <param name="type"></param>
        public void SubmitMessager(SiteEntity siteEntity,string type)
        {
            string message = type == "add" ? "有新的场地需要您审核！" : siteEntity.title+" 有修改，需要您审核！";
            List<ItemsDetailActionModel> F_ApplyType = GetItemList("sqlx");
            var crEntity = new CheckRecordEntity
            {
                F_OrderId = siteEntity.F_Id,
                F_ApplyUserId = siteEntity.F_LastModifyUserId,
                F_ApplyType = 1,
                F_CheckContent = message,
                F_CheckUserId = siteEntity.Mocha_ITOM
            };
            crEntity.Create();
            checkService.Insert(crEntity);

            // 1.2.1 批量生成流程通知(审核通知)
            var noticeEntity = new MessageNoticeEntity
            {
                F_MessageWay = 1,   /*消息类型1：个人通知，2，全部人通知*/
                F_ReceiveUserId = siteEntity.Mocha_ITOM,
                F_MessageType = 1,  /*消息类型1:审核通知，2：申请通知*/
                F_MessageContent = message,
                F_IsRead = 0        /*是否已读0：未读，1：已读*/
            };
            noticeEntity.Create();
            messageService.Insert(noticeEntity);
        }


        public void SubmitAttachmentForm(SiteEntity siteEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                siteEntity.Modify(keyValue);
                service.Update(siteEntity);
            }
        }
        public List<MetroItemsModel> GetMetroItemList(string enCode)
        {

            return itemsDetailApp.GetMetroItemList(enCode);
        }
        public List<ItemsDetailActionModel> GetItemList(string enCode)
        {

            return itemsDetailApp.GetItemList(enCode);
        }

        public List<ItemsDetailEntity> GetItemList(string enCode, string pid)
        {

            return itemsDetailApp.GetItemList(enCode, pid);
        }

        #region 场地大师APP接口

        public string SubmitSiteForm(SiteEntity siteEntity, string keyValue, List<PhotosEntity> imgList,List<CompanionSettingEntity> settingList)
        {
            using (var db = new RepositoryBase().BeginTrans())
            {
                if (!string.IsNullOrEmpty(keyValue))
                {
                    var LoginInfo = OperatorProvider.Provider.GetCurrent();
                    siteEntity.F_SupplierId = LoginInfo.UserId;
                    siteEntity.Modify(keyValue);
                    service.Update(siteEntity);

                    if (!String.IsNullOrEmpty(siteEntity.Mocha_ITOM))
                    {
                        var user=db.FindEntity<UserEntity>(siteEntity.Mocha_ITOM);
                        var EmailBody = "<p>" + siteEntity.title + "被场地方修改,请重新审核该场地</p>";
                        MailHelper mail = new MailHelper();
                        mail.MailServer = Configs.GetValue("MailHost");
                        mail.MailUserName = Configs.GetValue("venue-center");
                        mail.MailPassword = Configs.GetValue("venue-center-pwd");
                        var Subject = "【场地审核】";
                        var Emails = user.F_Email;
                        if (!String.IsNullOrEmpty(Emails))
                        {
                            mail.SendToAttachment(Emails, Subject, EmailBody, "");
                        }                        
                    }                    
                }
                else
                {
                    siteEntity.Create();
                    siteEntity.F_LastModifyTime = siteEntity.F_CreatorTime;
                    siteEntity.F_LastModifyUserId = siteEntity.F_CreatorUserId;
                    service.Insert(siteEntity);
                }
                if (imgList!=null && imgList.Count > 0)
                {
                    photosApp.updatePhotoList(imgList, siteEntity.F_Id);
                }
                db.Delete<CompanionSettingEntity>(p => p.f_siteId == siteEntity.F_Id && p.f_spaceId=="");
                if (settingList.Count > 0)
                {
                    settingList.ForEach(item =>
                    {
                        item.F_CreatorUserId = siteEntity.F_CreatorUserId;
                        item.f_siteId = siteEntity.F_Id;
                        item.f_spaceId = "";
                        item.Create();
                        db.Insert<CompanionSettingEntity>(item);
                    });
                }
                db.Commit();
            }
            return siteEntity.F_Id;
        }

        /// <summary>
        /// 用户场地列表
        /// </summary>
        public List<SiteMgrSiteActionModel> GetSites(string lastId, int count, string F_SupplierId, string F_Id, int state)
        {
            using (var db = new RepositoryBase())
            {
                var result = new List<SiteMgrSiteActionModel>();

                var strSql = @"SELECT site.F_Id, site.address, site.title , site.state,site.F_CreatorUserId F_CustomerId ,site.F_SupplierId,site.site_type,
	                            site.site_event_type,site.brand_story,site.city_id,site.district_id,site.level,site.F_Facilities,site.F_Category,
	                            (select count(1) from SL_Space where F_SiteId=site.F_Id ) as spacecount 
                                FROM SL_Site site  WHERE 1=1 {0}{2}{3}{4}  GROUP BY site.f_id ORDER BY site.F_CreatorTime DESC
                                LIMIT 0, {1};";

                if (!F_Id.IsNullOrEmpty())
                {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND site.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@lastId)", count,
                       " and site.F_SupplierId=@F_SupplierId", " and site.F_Id=@F_id", state >= 0 ? " and site.state=@state" : "");
                }
                else
                {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND site.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@lastId)", count,
                        " and site.F_SupplierId=@F_SupplierId", "", state >= 0 ? " and site.state=@state" : "");
                }
                DbParameter[] parameter =
                    {
                        new MySqlParameter("@state", state),
                        new MySqlParameter("@lastId", lastId),
                        new MySqlParameter("@F_SupplierId", F_SupplierId),
                        new MySqlParameter("@F_id",F_Id)
                    };
                result = db.FindList<SiteMgrSiteActionModel>(strSql, parameter);


                db.Commit();

                return result;
            }
        }

        /// <summary>
        /// 改变订单状态（申请上架、下架）
        /// </summary>
        /// <param name="keyValue"></param>
        /// <param name="state"></param>
        public string UpdateSiteState( string keyValue, int state,string customerId)
        {
            SiteEntity siteEntity = new SiteEntity();
            if (!string.IsNullOrEmpty(keyValue))
            {
                siteEntity.Modify(keyValue);
                siteEntity.state = state;
                siteEntity.F_LastModifyUserId = customerId;
                service.Update(siteEntity);
            }
            return keyValue;
        }
        #endregion


        #region 小程序
        /// <summary>
        /// 根据ID场地详情数据        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public WeCharSiteModel GetWeChatSiteDetails(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT s.title,s.site_type,s.site_event_type,s.brand_story,s.city_id,s.address,s.x_coordinates,s.y_conrdinates,
                                   s.district_id,s.nickname,s.recommend_reason,s.subway_distance,      
                                   s.ident,s.F_Id,s.F_Facilities,max(sp.max_seating_capacity) F_Max_seating_capacity,
                                   (SELECT F_FullName FROM Sys_Area sa
                               WHERE  sa.F_Id=s.city_id  ) cityname
                                ,(SELECT F_FullName FROM Sys_Area sa
                               WHERE   sa.F_Id = s.district_id ) district,
										 (SELECT F_FullName FROM Sys_Area sa
                               WHERE   sa.F_Id = s.business_area ) business_area,min(sp.F_YunPrice) as inner_price,sp.F_MarketPrice as market_price,sp.F_Units units
                from SL_Site s inner join SL_Space sp on s.f_id=sp.F_SiteId
                               and s.F_Id=@fId and s.state=1";
                
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue)
                };
                var SiteDetails = db.FindList<WeCharSiteModel>(strSql, parameter).FirstOrDefault();

                //获取场地所有评论数据
                var commentSql = @"select sum(F_SiteLike)likeCounts,F_SiteId as F_Id,format(sum(F_SiteLike)/count(F_SiteId),0) star from WeChat_Comment wc where wc.F_SiteId=@fId  group by wc.F_SiteId ";
                SiteDetails.SiteComment =  db.FindList<WeCharCommentModel>(commentSql, parameter).FirstOrDefault();

                return SiteDetails;
            }
        }
        /// <summary>
        /// 获取同类型场地
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public List<WeCharSiteModel> GetSimilarSitesList(string keyValue) {

            using (var db = new RepositoryBase())
            {
                string strSql = @"SELECT  s.title,s.site_type,s.site_event_type,s.brand_story,s.city_id,s.address,s.x_coordinates,s.y_conrdinates,
                                   s.district_id,s.nickname,s.recommend_reason,s.subway_distance,      
                                   s.ident,s.F_Id,s.F_Facilities,p.F_path,sp.F_Tags,
                                   format(sp.max_seating_capacity,0) F_Max_seating_capacity,
                                   format(sp.accept_weight,0)accept_weight,format(sp.height,0)height,format(sp.area,0)area,
                                   (SELECT F_FullName FROM Sys_Area sa
                               WHERE  sa.F_Id=s.city_id  ) cityname
                                ,(SELECT F_FullName FROM Sys_Area sa
                               WHERE   sa.F_Id = s.district_id ) district,
										 (SELECT F_FullName FROM Sys_Area sa
                               WHERE   sa.F_Id = s.business_area ) business_area,format(sp.F_YunPrice,0) as inner_price,format(sp.F_MarketPrice,0) as market_price,sp.F_Units units
                                from SL_Site s inner join 
					            (select min(sc.F_MarketPrice) as F_MarketPrice, sc.max_seating_capacity,sc.F_YunPrice,
                                sc.F_Units,F_SiteId,sc.accept_weight,sc.height,sc.area,sc.F_Tags from SL_Space sc where sc.state=1 group by F_SiteId)
					            sp on s.f_id=sp.F_SiteId inner join 
									SL_Photos p on s.F_Id=p.photoable_id and p.photoable_type='Site' and p.is_cover=1 and p.F_DeleteMark!=1
                            where site_type =
							(select si.site_type from SL_Site si where si.F_Id=@fId) 
							and city_id =
							(select si.city_id from SL_Site si where si.F_Id=@fId) 
							and s.F_Id not in(@fId) and s.state=1 group by s.F_Id order by rand()  limit 5";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue)
                };
                return db.FindList<WeCharSiteModel>(strSql, parameter);
            }
        }

        #endregion

        #region 小场地APP接口
        public List<string> GetHot5Site()
        {
            using (var db = new RepositoryBase())
            {
                string strSql = @"select a.F_HotId from MiniSite_HotSite a where a.F_Type=1";
                return db.FindList<string>(strSql);
            }
        }

        /// <summary>
        /// 精选场地
        /// </summary>
        public List<SiteHotActionModel> GetChoiceSites(string customerId)
        {
            var siteIds = GetHot5Site(); //commentService.GetTop5SiteCommentMost();
            if (siteIds.Any())
            {
                var count = siteIds.Count;

                var item1 = GetHotSitesByIds(siteIds, customerId);
                if (count < 5)
                {
                    var item2 = GetHotSites(customerId, "", 5 - count, siteIds);
                    item1.AddRange(item2);
                }
                return item1;
            }
            return GetHotSites(customerId, "", 5, siteIds);
        }

        public List<SiteHotActionModel> GetHotSitesByIds(List<string> ids, string customerId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT a.f_id,a.title,c.inner_price,a.address,a.brand_story,c.market_price,b.path f_PhotoUrl,5 starnumber,case when fa.f_favoriteid is null then 0 else 1 end isfavorite FROM SL_Site a
                         inner join (select max(a.F_Id) F_Id,max(a.inner_price) inner_price,max(a.market_price) market_price,a.F_SiteId from SL_Space a group by a.F_SiteId) c on a.F_Id=c.F_SiteId 
                         left join SL_Photos b on a.f_id=b.photoable_id and b.photoable_type='Site' 
                         left join (select distinct f_favoriteid from MiniSite_Favorite where  F_Status=1 AND  F_Type = 1  {1}) fa on a.F_Id=fa.F_FavoriteId  
                         WHERE a.F_Category = 1 and a.state=1 and a.f_id in({0}) GROUP BY a.f_id ORDER BY b.is_cover DESC";
                strSql = string.Format(strSql, string.Join(",", ids.Select(p => string.Format("'{0}'", p))), customerId.IsNullOrEmpty() ? "and F_CustomerId=''" : "and F_CustomerId=@customerId");
                DbParameter[] parameter =
                    {
                     new MySqlParameter("@customerId", customerId)
                    };
                return db.FindList<SiteHotActionModel>(strSql, parameter);
            }
        }

        public List<SiteHotActionModel> GetHotSites(string customerId, string lastId, int count, List<string> ids)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT a.f_id,a.title,c.inner_price,a.address,a.brand_story,c.market_price,b.path f_PhotoUrl,5 starnumber,case when fa.f_favoriteid is null then 0 else 1 end isfavorite FROM SL_Site a
                         inner join (select max(a.F_Id) F_Id,max(a.inner_price) inner_price,max(a.market_price) market_price,a.F_SiteId from SL_Space a group by a.F_SiteId) c on a.F_Id=c.F_SiteId 
                         left join SL_Photos b on a.f_id=b.photoable_id and b.photoable_type='Site'  
                         left join (select distinct f_favoriteid from MiniSite_Favorite where  F_Status=1 AND F_Type = 1  {1}) fa on a.F_Id=fa.f_favoriteid   
                         WHERE a.F_Category = 1 and a.state=1 {0} {2}
                        GROUP BY a.f_id   ORDER BY  a.F_CreatorTime DESC, b.is_cover DESC limit 0,@count";
                strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : "AND a.F_Id > @fId", customerId.IsNullOrEmpty() ? " and F_CustomerId=''" : "and F_CustomerId=@customerId", ids.Count > 0 ? "and a.f_id not in(" + string.Join(",", ids.Select(p => string.Format("'{0}'", p))) + ")" : "");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", lastId),
                    new MySqlParameter("@customerId", customerId),
                    new MySqlParameter("@count", count)
                };
                return db.FindList<SiteHotActionModel>(strSql, parameter);
            }
        }

        /// <summary>
        /// 热门预定
        /// </summary>
        public List<SiteHotActionModel> GetHotSites(string customerId)
        {
            var siteIds = orderService.GetTop5SiteOrderMost();
            if (siteIds.Any())
            {
                var count = siteIds.Count;

                var item1 = GetHotSitesByIds(siteIds, customerId);
                if (count < 5)
                {
                    var item2 = GetHotSites(customerId, "", 5 - count, siteIds);
                    item1.AddRange(item2);
                }
                return item1;
            }
            return GetHotSites(customerId, "", 5, siteIds);
        }

        public List<string> GetHot5Activty()
        {
            using (var db = new RepositoryBase())
            {
                string strSql = @"select a.F_HotId from MiniSite_HotSite a where a.F_Type=2";
                return db.FindList<string>(strSql);
            }
        }

        public List<ActivityHotActionModel> GetHotActivitys(string customerId)
        {
            var activityIds = GetHot5Activty();//activityService.GetTop5SiteActivityMost();
            if (activityIds.Any())
            {
                var count = activityIds.Count;
                var item1 = GetAcivityByIds(activityIds, customerId);
                if (count < 5)
                {
                    var item2 = GetActivitys(customerId, "", 5 - count, activityIds);
                    item1.AddRange(item2);
                }
                return item1;
            }
            return GetActivitys(customerId, "", 5, activityIds);
        }

        public List<ActivityHotActionModel> GetActivitys(string customerId, string lastId, int count, List<string> ids)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Content,a.F_Address,a.F_Price,a.F_CustomerId,a.F_SiteId,a.F_SpaceId,a.F_OrderId,d.path as f_PhotoUrl,
                        case when fa.f_favoriteid is null then 0 else 1 end isfavorite
                        from MiniSite_SiteActivity a                        
                        left join SL_Photos d on a.F_Id=d.photoable_id and d.is_cover=1
                        left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite WHERE  F_Status=1 AND  F_Type = 2  {1}) fa ON  fa.f_favoriteid = a.F_Id  
                        where 1=1 and a.F_IsPublic=1 {0} {2}  GROUP BY a.F_Id  ORDER BY d.is_cover DESC 
                        LIMIT 0, @count";
                strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : "AND a.F_Id > @fId", customerId.IsNullOrEmpty() ? "and F_CustomerId=''" : "and F_CustomerId=@customerId", ids.Count > 0 ? " and a.f_id not in(" + string.Join(",", ids.Select(p => string.Format("'{0}'", p))) + ")" : "");
                DbParameter[] parameter =
               {
                    new MySqlParameter("@fId", lastId),
                    new MySqlParameter("@customerId", customerId),
                    new MySqlParameter("@count", count)
                };
                return db.FindList<ActivityHotActionModel>(strSql, parameter);
            }
        }

        public List<ActivityHotActionModel> GetAcivityByIds(List<string> ids, string customerId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.F_Id,a.F_Title,a.F_Subject,a.F_Content,a.F_Address,a.F_Price,a.F_CustomerId,a.F_SiteId,a.F_SpaceId,a.F_OrderId,d.path as f_PhotoUrl,
                        case when fa.f_favoriteid is null then 0 else 1 end isfavorite
                        from MiniSite_SiteActivity a                        
                        left join SL_Photos d on a.F_SiteId=d.photoable_id
                        left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite where  F_Status=1  AND  F_Type = 2  {1}) fa on a.F_Id=fa.f_favoriteid
                        where a.F_IsPublic=1 and a.F_Id in({0})  GROUP BY a.F_Id  ORDER BY  d.is_cover DESC";
                strSql = string.Format(strSql, string.Join(",", ids.Select(p => string.Format("'{0}'", p))), customerId.IsNullOrEmpty() ? " and F_CustomerId=''" : "and F_CustomerId=@customerId");
                DbParameter[] parameter =
                {
                    new MySqlParameter("@customerId", customerId)
                };
                return db.FindList<ActivityHotActionModel>(strSql, parameter);
            }
        }

        /// <summary>
        /// 场地列表(获取最后的10条数)
        /// </summary>
        public List<SiteActionModel> GetSites(SiteSearchActionModel search, string lastId, int count, string customerId)
        {
            // 最新创建的 10 条数据 小场地类型为 F_Category = 1
            //return service.GetSites(lastId, count);

            using (var db = new RepositoryBase())
            {
                var result = new List<SiteActionModel>();

                var strSql = @"SELECT site.F_Id,site.F_Id F_SiteId, IFNULL(site.ident,'') F_Ident, site.address F_Address, site.title F_Title, IFNULL(min(space.market_price), 0)  F_LowestPrice, IFNULL(space.units,'') F_PriceUnit,
                                    IFNULL(photo.path,'') F_PhotoUrl ,IFNULL(photo.name,'') F_PhotoName,site.district_id,space.max_seating_capacity,site.site_type,site.site_style,
                                case when fa.F_CustomerId is null then 0 else 1 end isfavorite                             
                                FROM SL_Site site 
                                LEFT JOIN SL_Space space ON site.F_Id = space.F_SiteId  
                                LEFT JOIN SL_Photos photo ON  photo.photoable_id = site.F_Id AND photo.photoable_type='Site' 
                                left join (select distinct f_favoriteid,F_CustomerId from MiniSite_Favorite WHERE  F_Status=1 AND  F_Type = 1 and F_CustomerId=@customerId) fa on site.F_Id=fa.f_favoriteid
                                inner join Sys_ItemsDetail qu on site.district_id=qu.F_ItemCode                                
                                WHERE site.F_Category = 1 AND  site.state=1 AND space.state=1 {0} {1} {2} {3}  GROUP BY site.f_id
                                ORDER BY site.F_CreatorTime DESC";
                if (search == null)
                {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND site.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@fId)", count, "", "", "", "");
                }
                else {
                    strSql = string.Format(strSql, lastId.IsNullOrEmpty() ? "" : " AND site.F_CreatorTime<(select F_CreatorTime from SL_Site where F_Id=@fId)",
                    search.AreaId==null || search.AreaId <= 0 ? "" : " and site.district_id=@districtid",
                    search.MaxPeople==null || search.MaxPeople <= 0 ? "" : " and space.max_seating_capacity>=@min and space.max_seating_capacity<=@max",
                    search.KeyWords.IsNullOrEmpty() ? "" : " and site.title like '%" + search.KeyWords + "%' ");
                }

                DbParameter[] parameter =
                    {
                        new MySqlParameter("@fId", lastId),
                        new MySqlParameter("@customerId", customerId),
                        new MySqlParameter("@districtid", search==null?0:search.AreaId),
                        new MySqlParameter("@min", search==null?0:search.MinPeople),
                        new MySqlParameter("@max", search==null?0:search.MaxPeople)
                    };
                result = db.FindList<SiteActionModel>(strSql, parameter);
                List<SiteActionModel> listresult = new List<SiteActionModel>();
                if(search.SiteTypes!=null)
                {
                    result.ForEach(item => {
                        var ll = from ss in search.SiteTypes where ss.Contains(item.site_type) select ss;
                        if (ll.Count() > 0)
                        {
                            listresult.Add(item);
                        }
                    });
                }
                List<SiteActionModel> listresult2 = new List<SiteActionModel>();
                if (search.ActivityTypes != null) {
                    result.ForEach(item =>
                    {
                        var ll = from ss in search.ActivityTypes where ss.Equals(item.site_style) select ss;
                        if (ll.Count() > 0)
                        {
                            listresult2.Add(item);
                        }
                    });
                }

                var dataresut= result;
                if (listresult.Count == 0 && listresult2.Count > 0)
                {
                    dataresut = listresult2.Take(5).ToList();
                }
                else if (listresult.Count > 0 && listresult2.Count == 0)
                {
                    dataresut = listresult.Take(5).ToList();
                }
                else if (listresult.Count > 0 && listresult2.Count > 0) {
                    dataresut = listresult.Intersect(listresult2).Take(5).ToList();
                }              
                return dataresut;
            }
        }
        /// <summary>
        /// 根据ID获取场地详情数据（包括 城市、区域获取）
        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public SiteDetailActionModel GetSiteDetails(string keyValue)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT s.title,s.site_type,s.brand_story,s.city_id,s.address,s.x_coordinates,s.y_conrdinates,
                                s.district_id,s.nickname,s.recommend_reason,s.subway_distance,s.F_Attachment,s.F_AttachmentPpt,
                                s.business_area,s.ident,s.parking_space,s.F_Id,s.F_SupplierId,s.F_Keywords,s.F_Facilities,max(sp.max_seating_capacity) F_Max_seating_capacity,
                                (SELECT F_ItemName FROM Sys_ItemsDetail d    
                                    INNER JOIN Sys_Items i ON i.F_Id = d.F_ItemId
                            WHERE   1 = 1
                                    AND i.F_EnCode = 'City'
                                    AND d.F_EnabledMark = 1
                                    AND d.F_DeleteMark = 0
                                    AND d.f_itemCode = s.city_id ) cityname
                             ,(SELECT F_ItemName FROM Sys_ItemsDetail d
                                    INNER JOIN Sys_Items i ON i.F_Id = d.F_ItemId
                            WHERE   1 = 1
                                    AND i.F_EnCode = 'district'
                                    AND d.F_EnabledMark = 1
                                    AND d.F_DeleteMark = 0
                                    AND d.f_itemCode = s.district_id ) district,min(sp.inner_price) as inner_price,sp.market_price
					        from SL_Site s inner join SL_Space sp on s.f_id=sp.F_SiteId
                            and s.F_Id=@fId and s.state=1";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue)
                };
                return db.FindList<SiteDetailActionModel>(strSql, parameter).FirstOrDefault();
            }
        }
        /// <summary>
        /// 根据ID获取小场地详情数据        /// </summary>
        /// <param name="keyValue"></param>
        /// <returns></returns>
        public SiteDetailActionModel GetMiniSiteDetails(string keyValue, string customerId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"SELECT s.title,s.site_type,s.brand_story,s.city_id,s.address,s.x_coordinates,s.y_conrdinates,
                                s.district_id,s.nickname,s.recommend_reason,s.subway_distance,s.F_Attachment,s.F_AttachmentPpt,
                                s.business_area,s.ident,s.parking_space,s.F_Id,s.F_SupplierId,s.F_Keywords,s.F_Facilities,max(sp.max_seating_capacity) F_Max_seating_capacity,
                                (SELECT F_ItemName FROM Sys_ItemsDetail d    
                                    INNER JOIN Sys_Items i ON i.F_Id = d.F_ItemId
                            WHERE   1 = 1
                                    AND i.F_EnCode = 'City'
                                    AND d.F_EnabledMark = 1
                                    AND d.F_DeleteMark = 0
                                    AND d.f_itemCode = s.city_id ) cityname
                             ,(SELECT F_ItemName FROM Sys_ItemsDetail d
                                    INNER JOIN Sys_Items i ON i.F_Id = d.F_ItemId
                            WHERE   1 = 1
                                    AND i.F_EnCode = 'district'
                                    AND d.F_EnabledMark = 1
                                    AND d.F_DeleteMark = 0
                                    AND d.f_itemCode = s.district_id ) district,min(sp.inner_price) as inner_price,sp.market_price,(SELECT f.F_Status as isfavorite    FROM MiniSite_Favorite f  WHERE  f.F_Status =1 and f.F_Type=1  AND f.F_FavoriteId = s.F_Id  AND f.F_CustomerId=@customerId  ) as isfavorite
					        from SL_Site s inner join SL_Space sp on s.f_id=sp.F_SiteId
                            and s.F_Id=@fId and s.state=1";

                DbParameter[] parameter =
                {
                    new MySqlParameter("@fId", keyValue),
                new MySqlParameter("@customerId", customerId)
                };
                return db.FindList<SiteDetailActionModel>(strSql, parameter).FirstOrDefault();
            }
        }
        public List<CostRecordEntity> GetCostRecordListById(string orderId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select * 
                            from MiniSite_CostRecord a where a.F_OrderId=@orderId order by a.F_CreatorTime desc";
                DbParameter[] parameter =
                {
                    new MySqlParameter("@orderId", orderId)
                };
                return db.FindList<CostRecordEntity>(strSql, parameter);
            }
        }

        public List<SiteCostActionModel> GetSiteCostList(string siteId)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select a.f_id,a.f_siteId,a.f_costName,a.f_cost from MiniSite_Cost a where a.f_siteId=@siteid";
                DbParameter[] parameter = {
                    new MySqlParameter("@siteid",siteId)
                };
                return db.FindList<SiteCostActionModel>(strSql, parameter);
            }
        }

        public int SendMessageInfo(MessageRecordEntity entity)
        {
            using (var db = new RepositoryBase())
            {
                entity.Create();
                return db.Insert<MessageRecordEntity>(entity);
            }
        }

        public List<OrderStatusActionModel> GetOrderStatusById(string orderid)
        {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select case when b.f_operationType=0 then '下单' when b.f_operationType=1 then '已付定金' when b.f_operationType=2 then '档期确认,未付尾款'
                when b.f_operationType=3 then '订单完成' when b.f_operationType=6 then '申请退款' when b.f_operationType=7 then '退款完成'
                else '' end orderstate,
                b.F_CreatorTime as createtime from MiniSite_SiteOrder a 
                inner join MiniSite_orderStatusRecord b on a.F_Id=b.f_orderId
                where a.F_Id=@orderid";
                DbParameter[] parameter = {
                    new MySqlParameter("@orderid",orderid)
                };
                return db.FindList<OrderStatusActionModel>(strSql, parameter);
            }
        }

        public int InsertVistorRecord(SiteVistorRecordEntity entity) {
           return siteVistor.Insert(entity);
        }

        public string GetVistorNum(string supplierId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select count(*) as vistorNum from SL_Site a 
                                inner join Site_VistorRecord b on a.F_Id=b.F_SiteId where 
                                a.F_SupplierId=@supplierId and to_days(b.F_VistorTime)=to_days(now())";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.FindList<string>(strSql, parameter).FirstOrDefault();
            }
        }

        public string GetTodayOrderNum(string supplierId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select count(*) as todayOrderNum from MiniSite_SiteOrder a 
                                inner join SL_Site b on a.F_SiteId=b.F_Id
                                where b.F_SupplierId=@supplierId and a.F_Status=1 and to_days(a.F_CreatorTime)=to_days(now())";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.FindList<string>(strSql, parameter).FirstOrDefault();
            }
        }

        public decimal  GetTodayPayMoney(string supplierId) {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select ifnull(sum(pay.F_PayCash),0) as todayPayMoney from Site_PayFlowRecord pay
                            inner join MiniSite_SiteOrder so on pay.F_OrderId=so.F_Id
                            inner join SL_Site c on so.F_SiteId=c.F_Id
                            where c.F_SupplierId=@supplierId and to_days(pay.F_CreatorTime)=to_days(now())";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.GetColumnList<decimal>(strSql, parameter).FirstOrDefault();
            }
        }

        public string GetWaitOrderNum(string supplierId) {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select count(*) as waitOrderNum from MiniSite_SiteOrder a 
                                inner join SL_Site b on a.F_SiteId=b.F_Id
                                where b.F_SupplierId=@supplierId and a.F_Status=2
                                and to_days(a.F_CreatorTime)=to_days(now())";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.FindList<string>(strSql, parameter).FirstOrDefault();
            }
        }

        public decimal  GetLastPayMoney(string supplierId) {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select ifnull(sum(pay.F_PayCash),0) as todayPayMoney from Site_PayFlowRecord pay
                            inner join MiniSite_SiteOrder so on pay.F_OrderId=so.F_Id
                            inner join SL_Site c on so.F_SiteId=c.F_Id
                            where c.F_SupplierId=@supplierId and to_days(now())-to_days(pay.F_CreatorTime)=1";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.GetColumnList<decimal>(strSql, parameter).FirstOrDefault();
            }
        }

        public string GetLastOrderNum(string supplierId) {
            using (var db = new RepositoryBase())
            {
                var strSql = @"select count(*) as lastOrderNum from Site_PayFlowRecord pay
                            inner join MiniSite_SiteOrder so on pay.F_OrderId=so.F_Id
                            inner join SL_Site c on so.F_SiteId=c.F_Id
                            where c.F_SupplierId=@supplierId and to_days(now())-to_days(pay.F_CreatorTime)=1";
                DbParameter[] parameter = {
                    new MySqlParameter("@supplierId",supplierId)
                };
                return db.FindList<string>(strSql, parameter).FirstOrDefault();
            }
        }
        #endregion

        /// <summary>
        /// 获取场地地图列表信息
        /// </summary>
        /// <returns></returns>
        public List<SiteMapDto> GetSiteMaps()
        {
            return service.GetSiteMaps();
        }

        /// <summary>
        /// 获取场地柱状图列表信息
        /// </summary>
        /// <returns></returns>
        public List<SiteBarDto> GetSiteBarData(string provinceId)
        {
            return service.GetSiteBarData(provinceId);
        }

        /// <summary>
        /// 获取场地柱状图和折线列表信息
        /// </summary>
        /// <returns></returns>
        public List<SiteBarDto> GetSiteBarAndLineData(string provinceId)
        {
            return service.GetSiteBarAndLineData(provinceId);
        }
    }
}

